# -*- coding: utf-8 -*-
import asyncio

import botpy
from botpy import logging
from botpy.message import Message
from sparkai.core.outputs import LLMResult

from config_set import config_instance
from xinghuo_api import get_xinghuo_response

_log = logging.get_logger()


class MyClient(botpy.Client):
    async def on_ready(self):
        _log.info(f"robot 「{self.robot.name}」 on_ready!")

    async def on_at_message_create(self, message: Message):
        # _log.info(message.author.avatar)
        if "sleep" in message.content:
            await asyncio.sleep(10)
        _log.info(f"{message.author.username}: {message.content}")
        _log.info(f"message.member:{message.member}:message.id:{message.id}")

        res = get_xinghuo_response(message.content)
        # 从结果中提取回复文本
        if isinstance(res, LLMResult):
            # 通常 generations 是一个二维列表，这里假设取第一个生成结果
            first_generation = res.generations[0][0]
            reply_text = first_generation.text

            await message.reply(content=reply_text)
            # 图片消息
            # await message.reply(content=f"机器人{self.robot.name}收到你的@消息了: {message.content}",
            #                     file_image="resource/zhichao-cheng.jpg")
        else:
            await message.reply(content="听不懂一点")


if __name__ == "__main__":
    # 通过kwargs，设置需要监听的事件通道
    intents = botpy.Intents(public_guild_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=config_instance["appid"], secret=config_instance["secret"])
